
var accessid= 'LTAI4FpGGLfQc4qwSaghn16j';
var accesskey= 'hBYnag1SUhFfuP2HvfqLWVvuN9ZOGh';
var host = ossUrl;

var g_dirname = 'qz/'
g_dirname =""
var g_object_name = ''
var g_object_name_type = 'random_name'
var now = timestamp = Date.parse(new Date()) / 1000;

var policyText = {
    "expiration": "2025-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
        ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = Crypto.util.bytesToBase64(bytes);

function uploadOnePicToOss (path ,func) {
    let client = new OSS({
        region: 'oss-cn-qingdao',
        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用STS方式来进行API访问
        accessKeyId: accessid,
        accessKeySecret: accesskey,
        // stsToken: '<Your securityToken(STS)>',
        bucket: 'localservices'
    });
    var trans = api.require('trans');
    trans.decodeImgToBase64({
        imgPath: path
    }, function(ret, err) {

        // logJson(ret,"111")
        // logJson(err,"222")
        if (ret.status) {
            var base64Str = ret.base64Str;
            // logJson(base64Str)
            let Blob = convertBase64UrlToBlob(base64Str)

            const data = Blob;
            let newFileName = random_string() + random_string() + get_suffix(path);
            try {
                // object-key可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
                client.put(g_dirname + newFileName, data).then((result)=>{
                    logJson(result);
                    if (result.res.statusCode === 200) {
                        // let picUrl = host + "/" + g_dirname + newFileName
                        let picUrl = "/" + g_dirname + newFileName
                        func(picUrl)
                    }
                });

            } catch (e) {
                logJson(e);
            }

        } else {
            alert(err.msg);
        }
    });





}
/**
 * 将以base64的图片url数据转换为Blob
 * @param urlData
 *            用url方式表示的base64图片数据
 */
function convertBase64UrlToBlob(urlData){

    var bytes=window.atob(urlData);        //去掉url的头，并转换为byte

    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }

    return new Blob( [ab] , {type : 'image/png'});
}
function uploadOnePicToOss_old (path ,func) {
    logJson(path,"2008251050")
    var newFileName = random_string() + random_string() + get_suffix(path);
    var param = {
        'key' : g_dirname + newFileName,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'Signature': signature,
    }
    api.ajax({
        url: host,
        method: 'POST',
        returnAll:true,
        headers: {
            "token":api.deviceId
            ,"Cookie": cookie()
        },
        dataType:"xml",
        processData:false,
        data:  {
            values:param,
            files:{
                file:path
            }
        }
    }, function(ret, err) {
        logJson(ret,"oss_ret")
        logJson(err,"oss_err")
        if (err === '') {
            // let picUrl = host + "/" + g_dirname + newFileName
            let picUrl = "/" + g_dirname + newFileName
            func(picUrl)
        }
    });
}



function random_string(){
    var len = 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0;i<len;i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}
